<?php
namespace App\Services;
use Illuminate\Support\Str;
class VerificationCodeService{

    /**
     * @param $phone 生成并发送验证码的手机号
     * @return array 包含手机号、验证码value的随机key和过期时间
     * @throws \Exception
     */
    //生成手机号验证码
    public function createPhoneCode($phone){

        if (!app()->environment('production')) {
            $code = '1234';
        } else {
            // 生成4位随机数，左侧补0
            $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
            $is_true = send_weimi_short_msg($phone,$code);
            if (!$is_true){
                abort(500,"错误的信息");
            }
        }
        $key = 'verificationCode_'.Str::random(15);
        $expiredAt = now()->addMinutes(5);
        // 缓存验证码 5分钟过期。
        \Cache::put($key, ['phone' => $phone, 'code' => $code], $expiredAt);
        return [
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ];
    }
}
